<?php

namespace App\V3\V3_2\Controllers;

use App\V3\V3_2\Services\OutInRepealService;
use App\V3\V3_2\Services\SalesReturnService;
use App\Helper\Utils\TimeUtil;
use App\V3\V3_2\Models\SalesReturnModel;
use App\V3\V3_2\Models\SalesReturnPayRecordModel;
use App\V3\V3_2\Services\IncomeExpensesService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Rules\JsonArray;

class SalesReturnController extends BaseController
{
    //退货单批次号列表
    public function salesReturnBatchList(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'materiel_type_id' =>'required',//页面大小

            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页

        ],[
            'materiel_type_id.required' => '参数`商品id`缺失',
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $list = SalesReturnService::salesReturnBatchList($request->materiel_type_id,$data);
        $this->log('退货单批次号列表', $list);
        return $this->success($list);
    }

    //退货单序列号
    public function salesReturnSerialNumber(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
//            'materiel_type_id' =>'required',//页面大小

            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
//            'materiel_type_id.required' => '参数`商品id`缺失',
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
            if(!isset($data['status'])){

                $data['status']=88;
            }
            $list = SalesReturnService::salesReturnSerialNumber($request->materiel_type_id,$data['status'],$data);
            if(!empty($list['code'])&& $list['code'] == 1){
               return $this->fail('','商品信息，不存在！');
            }
            $this->log('退货单序列号', $list);
            return $this->success($list);
    }

    /**
     * 退货单设置批次号
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/9/9 17:23
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellAddBatch(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'info' => [
                'required',
                'json',
                new JsonArray([
                    'batch_id' => 'required|numeric',//批次id
                    'storage_manage_id' => 'required|numeric|',//库存id
                    'num' => 'required|numeric' //要使用的批次数量
                ])
            ],
            'id' => 'required|numeric',//销售单内商品或销售单内套餐商品id
            'return_id' => 'required|numeric|', //销售单id
            'type' => [
                'required',
                Rule::In([0,1]),
            ],//条码类型0:商品;1:套餐;
        ],[
            'id.required' => '参数`退货单内商品或退货单内套餐商品id`缺失',
            'return_id.required' => '参数`sell_id`缺失',
            'return_id.numeric' => '参数`sell_id`类型错误',
            'type.required' => '参数`type`缺失',
            'type.In' => '参数`type`不合法',
            'info.required' => '参数`info`缺失',
            'info.json' => '参数`info`仅能为json',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();
        //        $data['user_id'] = $this->getUserId();

        $this->log('设置批次号', $data);
        return response()->json(
            SalesReturnService::sellAddBatch($data)
            );
    }

    /**
     * 添加退货单
     * change 在 2021/11/3 15:21 创建
     * modify by Sw at 2022-4/28 15:03
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'customer_name' =>'required|string',//客户姓名
            /* 'discount' =>'integer',//折扣 ：百分比
            'tax_rate' =>'integer',//税率 ：百分比 */
            'is_zero_suppression' =>'required|integer',//是否改价：0-否 1-是
            'final_money' =>'string',//实际应收金额（即折扣或抹零后价格）如果是改价此参数必填
            'real_money' =>'string',//实付金额（实际入账）
            'remark' =>'string',//备注
            'out_order_no' =>'string',//外部单号
            'refund_date' =>'required|date',//退货时间
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            //            'is_draft' =>'required|integer',//是否草稿：1-是 0-否
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //报溢报损主单
        $mainInfo = $data;
        unset($mainInfo['goods_info']);
        unset($mainInfo['package_info']);
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $mainInfo['main_id'] = $this->getMainUserId();
        $mainInfo['user_id'] = $this->getUserId();
        $mainInfo['created_at'] = time();
        $mainInfo['refund_date'] = strtotime($data['refund_date']);
        $mainInfo['order_no'] = 'ST'. $this->getMainUserId().TimeUtil::getMillisecond();//订单号

        return response()->json(
            SalesReturnService::add($mainInfo, $data)
        );
    }

    /**
     * 退货单详细 with token
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/4/30 15:56
     * @return \Illuminate\Http\JsonResponse
     */
    public function find(Request $request)
    {
        //参数验证
        $validator = Validator::make($request->except('role_id'), [
            'id' =>'required|integer',//退货单主键id
        ],[
            'id.required' => '参数`退货单id`是必须的'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(
            SalesReturnService::find($request->id)
        );
    }

    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//主键id
            'customer_name' =>'string',//客户姓名
            'goods_info' =>'string',//商品信息  json array [{"name":"测试","type_name":"规格","price":"2.30","num":2,"image":"商品图片地址","warehouse":"仓库名称","warehouse_id":1},{"name":"测试1","type_name":"规格","price":"2.30","num":22,"image":"商品图片地址","warehouse":"仓库名称1","warehouse_id":2}]
            /* 'discount' =>'integer',//折扣 ：百分比
            'tax_rate' =>'integer',//税率 ：百分比 */
            'is_zero_suppression' =>'required|integer',//是否改价：0-否 1-是
            'final_money' =>'string',//实际应收金额（即折扣或抹零后价格）如果是改价此参数必填
            'real_money' =>'string',//实付金额（实际入账）
            'remark' =>'string',//备注
            'out_order_no' =>'string',//外部单号
            'refund_date' =>'date',//退货时间
            'proof_image' =>'string',//凭证图片(多图逗号分隔)
            //            'is_draft' =>'required|integer',//是否草稿：1-是 0-否
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['refund_date'] = isset($data['refund_date'])?strtotime($data['refund_date']):time();

        //报溢报损主单
        $mainInfo = $data;
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();

        return response()->json(
            SalesReturnService::edit($mainInfo, $data)
        );
    }

    public function repeal(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//退货单主键
        ],[
            'id.required' => '参数`退货单id`是必须的'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $this->log('退货单撤销', $data);
        return response()->json(
            OutInRepealService::repeal($data['id'],2)
        );
    }

    /**
     * 入库
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/15 17:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function in(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' => 'required|integer',//退货单主键id
            'status' => 'required|integer',//出入库状态：0-部分 1-全部
            'in_storage_time'=>'required|date',//入库时间
            'remark' => 'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['out_way'] = $this->getOutWay();

        //$data['is_use_serial'] = $this->isUseSerial();

            /* if($data['out_way'] == 1) {

                $result = SalesReturnService::outWithBatch($data);
            }
            else {

                $result = SalesReturnService::in($data);
            } */

        $result = SalesReturnService::frontReturnIn($data);
            $this->log('退货入库', $result);
            return response()->json($result);
    }

    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|numeric|min:1',//页面大小
            'currentPage' => 'required|numeric|min:1',//当前页码
            'search_type'=>[
                'required',
                Rule::In([1,2,3,4,5,6,7,8])
            ],
            'status'=>[
                'required',
                Rule::In([0,1,2,3,4,5,6])
            ],
            'repeal_status'=>[
                'required',
                Rule::In([0,1])
            ]
        ],[
            'pageSize.required' => '参数`页面大小`缺失',
            'pageSize.numeric' => '参数`页面大小`仅能为数字',
            'pageSize.min' => '参数`页面大小`最小只能为1',
            'currentPage.required' => '参数`页码`缺失',
            'currentPage.numeric' => '参数`页码`仅能为数字',
            'currentPage.min' => '参数`页码`最小只能为1',
            'search_type.required' => '参数`搜索类型`缺失',
            'search_type.in' => '参数`搜索类型`不合法',
            'status.required' => '参数`状态`缺失',
            'status.in' => '参数`状态`不合法',
            'repeal_status.required' => '参数`撤销状态`缺失',
            'repeal_status.in' => '参数`撤销状态`不合法',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(isset($request->start_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'start_time' => 'date_format:Y-m-d H:i:s',//页面
            ],[
                'start_time.date_format' => '开始时间格式错误，例：'.date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        if(isset($request->end_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'end_time' => 'date_format:Y-m-d H:i:s',//页面
            ],[
                'end_time.date_format' => '结束时间格式错误，例：'.date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        if($this->getUserId() == $this->getMainUserId() || $this->isShareReturn()){
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $userId['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            SalesReturnService::list($userId, $data)
        );
    }

    public function payHistory(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ],[
            'id.required' => '参数`退货单id`是必须的'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            SalesReturnService::payHistory($request->id)
        );
    }

    /**
     * 付款
     * change 在 2021/11/1 16:47 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMoney(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'return_id'=>'required|integer',//退货单主键
//            'money'=>'numeric|min:0',//收款金额
            'collection_time'=>'required|date',//收款时间
            'collection_account'=>'required|string',//收款账号
            'status'=>'required|integer',//收款状态：1-全部 2-部分
        ], [
            'money.numeric' => '金额异常，只能为数字，请重新输入',
            'money.min' => '金额不能低于0'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            $model = SalesReturnModel::where('id',$data['return_id'])->first();//销售单信息
            $inMomey = SalesReturnPayRecordModel::where('return_id',$data['return_id'])->sum('money');//已收款金额
            //全部收款
            if($data['status']==1){
                $model->pay_status = 2;
                $model->real_money = $model->final_money;
                $model->save();
                $money = $model['final_money']-$inMomey;
            }else{//部分收款
                //收款超额检测
                if(($inMomey+$data['money'])>$model['final_money']){
                    return $this->fail('', '超出剩余应付金额');
                }
                if(($inMomey+$data['money'])<$model['final_money']){
                    $model->pay_status = 1;
                    $model->real_money = $inMomey+$data['money'];
                }
                if(($inMomey+$data['money'])==$model['final_money']){
                    $model->pay_status = 2;
                    $model->real_money = $model->final_money;
                }
                $model->save();
                $money = $data['money'];
            }
            //收款记录
            $data['collection_time'] = strtotime($data['collection_time']);
            $data['created_at'] = time();
            $data['main_id'] = $this->getMainUserId();
            unset($data['status']);
            $data['money'] = $money;
            SalesReturnPayRecordModel::insert($data);

            //账单记录
            IncomeExpensesService::tally(1,$model['order_no'],$money,$this->getMainUserId(), $model['refund_date']);
            DB::commit();//提交事务
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail('','$e->getMessage()');
        }
    }

    /**
     * 删除退货单
     * change 在 2021/11/2 15:51 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        SalesReturnModel::where('id', $data['id'])->update(['delete_flag' => 1]);
        return $this->success();
    }
}
